package com.ruoyi.framework.web.service;

import com.alipay.api.AlipayApiException;
import com.alipay.api.response.AlipayFundTransUniTransferResponse;
import com.ruoyi.common.core.domain.DTO.WapTransferBO;
import com.ruoyi.common.core.domain.entity.UserPoints;
import com.ruoyi.common.core.domain.entity.UserPointsLog;
import com.ruoyi.common.utils.zfb.AlipayFundTransUniTransferWap;
import com.ruoyi.system.mapper.PointsMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;

@Slf4j
@Component
@Transactional
public class PointsService {
    @Autowired
    private PointsMapper pointsMapper;

    /**
     * 保存积分记录
     */
    public void insertUserPointsLog(UserPointsLog userPointsLog) {
        pointsMapper.insertUserPointsLog(userPointsLog);
    }

    /**
     * 查询积分记录
     */
    public List<UserPointsLog> selectUserPointsLogByUserId(Long userId) {
        return pointsMapper.selectUserPointsLogByUserId(userId);
    }

    /**
     * 保存总积分
     */
    public void insertUserPoints(UserPoints userPoints) {
        pointsMapper.insertUserPoints(userPoints);
    }

    /**
     * 查询总积分
     */
    public UserPoints selectUserPointsByUserId(Long userId) {
        return pointsMapper.selectUserPointsByUserId(userId);
    }

    /**
     * 更新总积分
     */
    public void updateUserPoints(UserPoints userPoints) {
        pointsMapper.updateUserPoints(userPoints);
    }

    /**
     * 查询等级为2的用户
     */
    public List<Long> selectLevelTwoUserId(){
        return pointsMapper.selectLevelTwoUserId();
    }

    /**
     * 升级用户等级
     */
    public void updateLevel(Long userId){

        UserPoints userPoints = pointsMapper.selectUserPointsByUserId(userId);
        if(ObjectUtils.isEmpty(userPoints)){
            //新增一条记录
            userPoints = new UserPoints();
            userPoints.setUserId(userId);
            userPoints.setLevel(2);
            pointsMapper.insertUserPoints(userPoints);
        } else if (userPoints.getLevel() == 1) {
            userPoints.setLevel(2);
            pointsMapper.updateUserPoints(userPoints);
        } else if (userPoints.getLevel() == 2) {
            throw new RuntimeException("用户已是会员，无需升级");
        }
    }

    private String generateOrderNo() {
        // 使用Snowflake算法生成唯一ID，然后补0到18位
        long timestamp = System.currentTimeMillis();
        long nodeId = 1L; // 节点ID
        long sequence = (long) (Math.random() * 1000); // 序列号

        String orderNo = String.valueOf((timestamp << 22) | (nodeId << 12) | sequence);
        // 确保是18位
        while (orderNo.length() < 18) {
            orderNo = "0" + orderNo;
        }
        return orderNo.length() > 18 ? orderNo.substring(0, 18) : orderNo;
    }
}
